package com.wish.g04.renting.config;

import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.xwpf.NiceXWPFDocument;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.text.pdf.security.DigestAlgorithms;
import com.itextpdf.text.pdf.security.MakeSignature;
import com.wish.g04.file.config.Textfile;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.util.Units;
import org.apache.poi.xwpf.converter.pdf.PdfConverter;
import org.apache.poi.xwpf.converter.pdf.PdfOptions;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.apache.xmlbeans.XmlException;
import org.openxmlformats.schemas.drawingml.x2006.main.CTGraphicalObject;
import org.openxmlformats.schemas.drawingml.x2006.wordprocessingDrawing.CTAnchor;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTDrawing;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTR;
import org.springframework.core.io.ClassPathResource;

import javax.swing.*;
import java.io.*;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.cert.Certificate;
import java.util.List;
import java.util.Map;

/**
 * 这个类的作者是123
 * 开发的日期是：2022/06/05
 **/
@Slf4j
public class FileUtils {
    public static final String KEYSTORE = "D:\\a-mycold\\zhengshu\\p12test.keystore";
    // 之前生成的keystory密码
    public static final char[] PASSWORD = "sangou".toCharArray();
    public static final String IMG = "D:\\yyjphoto\\7J5)S{LRQI6H{6A[46QCMWC.png";
//    private static Logger logger = LoggerFactory.getLogger(FileUtils.class);
    /**
     *  渲染Word 文件
     * @param templatePath   文件模板路径
     * @param fileDir        生成文件的路径
     * @param fileName       生成的文件名
     * @param paramMap       数据
     * @return
     */
    public static String createWord(String templatePath, String fileDir, String fileName, Map<String, Object> paramMap) {
        String name = "";//返回的文件名称
        File dir = new File(fileDir);
        if (!dir.exists()) {
            log.info("目录不存在，创建文件夹{}!", fileDir);
            dir.mkdirs();
        }
        String filePath = fileDir +"/"+ fileName+".docx";
        XWPFTemplate template = XWPFTemplate.compile(templatePath).render(paramMap);
        try {
            //这个不能删
            template.writeToFile(filePath);
            Textfile textfile = new Textfile();
            File file = new File(filePath);

            try {
                FileInputStream fis = new FileInputStream(file);
                XWPFDocument xdoc = new XWPFDocument(fis);
                XWPFWordExtractor extractor = new XWPFWordExtractor(xdoc);
                String doc1 = extractor.getText();
                System.out.println(doc1);
                name = createdPDF(doc1, fileDir, fileName);
                fis.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            //上传到七牛
            textfile.upload(fileDir,name);
            template.close();
        } catch (Exception e) {
            log.error("生成word异常{}", e.getMessage());
            e.printStackTrace();
        }finally {
//            File file = new File(filePath);
//            file.delete();
        }
        return name;
    }

    public static CTAnchor getAnchorWithGraphic(CTGraphicalObject ctGraphicalObject,
                                                String deskFileName, int width, int height,
                                                int leftOffset, int topOffset, boolean behind) {
        String anchorXML =
                "<wp:anchor xmlns:wp=\"http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing\" "
                        + "simplePos=\"0\" relativeHeight=\"0\" behindDoc=\"" + ((behind) ? 1 : 0) + "\" locked=\"0\" layoutInCell=\"1\" allowOverlap=\"1\">"
                        + "<wp:simplePos x=\"0\" y=\"0\"/>"
                        + "<wp:positionH relativeFrom=\"column\">"
                        + "<wp:posOffset>" + leftOffset + "</wp:posOffset>"
                        + "</wp:positionH>"
                        + "<wp:positionV relativeFrom=\"paragraph\">"
                        + "<wp:posOffset>" + topOffset + "</wp:posOffset>" +
                        "</wp:positionV>"
                        + "<wp:extent cx=\"" + width + "\" cy=\"" + height + "\"/>"
                        + "<wp:effectExtent l=\"0\" t=\"0\" r=\"0\" b=\"0\"/>"
                        + "<wp:wrapNone/>"
                        + "<wp:docPr id=\"1\" name=\"Drawing 0\" descr=\"" + deskFileName + "\"/><wp:cNvGraphicFramePr/>"
                        + "</wp:anchor>";

        CTDrawing drawing = null;
        try {
            drawing = CTDrawing.Factory.parse(anchorXML);
        } catch (XmlException e) {
            e.printStackTrace();
        }
        CTAnchor anchor = drawing.getAnchorArray(0);
        anchor.setGraphic(ctGraphicalObject);
        return anchor;
    }

    public static String createdPDF(String text,String filePath,String fileName)   {
        try {
            //创建文件
            Document document = new Document();
            //设置字体
            BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            //创建PDF
            PdfWriter writer = PdfWriter.getInstance(document, new
                    FileOutputStream(filePath + fileName + ".pdf"));
            // 设置页面布局
            writer.setViewerPreferences(PdfWriter.PageLayoutOneColumn);
            //打开文件
            document.open();
            //段落的间距
            Paragraph paragraph = new Paragraph(15);
            //对齐方式     1 2 3代表中右左
            paragraph.setAlignment(3);
            //字体
            Font fontHeader = new Font(bfChinese);
            //字体大小
            fontHeader.setSize(10);
            //设置段落字体
            paragraph.setFont(fontHeader);
            Chunk chunk1 = new Chunk(text);
            paragraph.add(chunk1);
            document.add(paragraph);
            //字体
            Font fontTable = new Font(bfChinese);
            //字体大小
            fontTable.setSize(8);
            //关闭文档
            document.close();
            //关闭书写器
            writer.close();
            String SRC = filePath+fileName+".pdf";
            String OUTPUT_SRC = filePath+"yyj"+fileName+".pdf";
            //加电子签章、证书
            try {
                //读取keystore ，获得私钥和证书链
                KeyStore keyStore = KeyStore.getInstance("JKS");
                keyStore.load(new FileInputStream(KEYSTORE), PASSWORD);
                String alias = (String)keyStore.aliases().nextElement();
                PrivateKey PrivateKey = (PrivateKey) keyStore.getKey(alias, PASSWORD);
                Certificate[] chain = keyStore.getCertificateChain(alias);

                KeystoreUtils keystoreUtils = new KeystoreUtils();
                keystoreUtils.sign(SRC, String.format(OUTPUT_SRC, 3),IMG, chain, PrivateKey, DigestAlgorithms.SHA1, null, MakeSignature.CryptoStandard.CMS, "Test", "Ghent");
            } catch (Exception e) {
                JOptionPane.showMessageDialog(null, e.getMessage());
                e.printStackTrace();
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "yyj"+fileName+".pdf";
    }

}
